package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.adapter.SpecialityAdapter;
import com.moyun.modelclass.adapter.UserInfoArticleAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.base.BaseConfig;
import com.moyun.modelclass.dialog.ScanImageDialog;
import com.moyun.modelclass.dialog.ShareDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppArticleDetailsApi;
import com.moyun.modelclass.http.api.CheckCollectListUserApi;
import com.moyun.modelclass.http.api.CheckFollowListUserApi;
import com.moyun.modelclass.http.api.CollectArticleApi;
import com.moyun.modelclass.http.api.FollowUserApi;
import com.moyun.modelclass.http.api.HomeFindApi;
import com.moyun.modelclass.http.api.UserInfoApi;
import com.moyun.modelclass.http.bean.ArticleResponse;
import com.moyun.modelclass.http.bean.LoginInfoResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.WechatShareUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelmsg.GetMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * tip：个人信息
 */
public class UserInfoActivity extends BaseActivity implements UserInfoArticleAdapter.OnFollowClick {
    private SmartRefreshLayout userInfoRefresh;
    private RecyclerView userInfoRecycler;

    private ImageView ivUserInfoBackgroundImage;
    private ImageView ivUserInfoBack;
    private ImageView ivUserInfoShare;
    private ImageView ivUserInfoHeadPortrait;
    private TextView tvUserInfoName;
    private ImageView ivUserInfoGender;
    private TextView tvUserInfoJob;
    private TextView tvUserInfoTitle;
    private RecyclerView rvUserInfoRecycler;
    private TextView tvUserInfoModelNum;
    private ImageView tvUserInfoIsFollow;
    private ImageView tvUserInfoChat;
    private LinearLayout llUserInfoCenterAll;
    private TextView tvUserInfoDetails;

    private UserInfoArticleAdapter userInfoArticleAdapter = new UserInfoArticleAdapter();
    private SpecialityAdapter specialityAdapter = new SpecialityAdapter();
    private List<String> articleIdList = new ArrayList<>();
    private String mLastId = "";
    private String mUserId = "";
    private boolean isFollow = false;
    private LoginInfoResponse loginInfo = null;

    public static void start(Context context, String userId) {
        Intent starter = new Intent(context, UserInfoActivity.class);
        starter.putExtra("userId", userId);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void assignViews() {
        userInfoRefresh = (SmartRefreshLayout) findViewById(R.id.user_info_refresh);
        userInfoRecycler = (RecyclerView) findViewById(R.id.user_info_recycler);

        userInfoRecycler.setLayoutManager(new LinearLayoutManager(this));
        userInfoArticleAdapter.setOnFollowClick(this);
        userInfoHeaderView();
        userInfoRecycler.setAdapter(userInfoArticleAdapter);
    }

    @SuppressLint("MissingInflatedId")
    private void userInfoHeaderView() {
        View header = LayoutInflater.from(mContext).inflate(R.layout.head_user_info, null);
        ivUserInfoBackgroundImage = (ImageView) header.findViewById(R.id.iv_user_info_background_image);
        ivUserInfoBack = (ImageView) header.findViewById(R.id.iv_user_info_back);
        ivUserInfoShare = (ImageView) header.findViewById(R.id.iv_user_info_share);
        ivUserInfoHeadPortrait = (ImageView) header.findViewById(R.id.iv_user_info_head_portrait);
        tvUserInfoName = (TextView) header.findViewById(R.id.tv_user_info_name);
        ivUserInfoGender = (ImageView) header.findViewById(R.id.iv_user_info_gender);
        tvUserInfoJob = (TextView) header.findViewById(R.id.tv_user_info_job);
        tvUserInfoTitle = (TextView) header.findViewById(R.id.tv_user_info_title);
        rvUserInfoRecycler = (RecyclerView) header.findViewById(R.id.rv_user_info_recycler);
        tvUserInfoModelNum = (TextView) header.findViewById(R.id.tv_user_info_model_num);
        tvUserInfoIsFollow = (ImageView) header.findViewById(R.id.tv_user_info_is_follow);
        tvUserInfoChat = (ImageView) header.findViewById(R.id.tv_user_info_chat);
        llUserInfoCenterAll = (LinearLayout) header.findViewById(R.id.ll_user_info_center_all);
        tvUserInfoDetails = (TextView) header.findViewById(R.id.tv_user_info_details);

        userInfoArticleAdapter.addHeaderView(header);

        rvUserInfoRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvUserInfoRecycler.setAdapter(specialityAdapter);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivUserInfoBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //分享
        ClickUtils.applySingleDebouncing(ivUserInfoShare, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginInfo != null) {
                    ShareDialog.getInstance(UserInfoActivity.this,
                            CommonConfiguration.splitResUrl(5, loginInfo.getBackgroundImage()),
                            loginInfo.getNickName(), new ShareDialog.OnShareListener() {
                                @Override
                                public void wx(Bitmap resource) {
                                    WechatShareUtils.wxShare(
                                            UserInfoActivity.this,
                                            loginInfo.getNickName(),
                                            loginInfo.getDesc(),
                                            resource);
                                }

                                @Override
                                public void pyq(Bitmap resource) {
                                    WechatShareUtils.pyqShare(
                                            UserInfoActivity.this,
                                            loginInfo.getNickName(),
                                            loginInfo.getDesc(),
                                            resource);
                                }
                            }).builder().setNegativeButton().show();
                }
            }
        });

        ClickUtils.applySingleDebouncing(tvUserInfoIsFollow, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关注
                EasyHttp.post(UserInfoActivity.this)
                        .api(new FollowUserApi().setUserId(mUserId).setFollow(!isFollow))
                        .request(new HttpCallback<HttpData<String>>(UserInfoActivity.this) {
                            @Override
                            public void onSucceed(HttpData<String> result) {
                                isFollow = !isFollow;
                                if (isFollow) {
                                    tvUserInfoIsFollow.setBackgroundResource(R.drawable.icon_follow_not);
                                } else {
                                    tvUserInfoIsFollow.setBackgroundResource(R.drawable.icon_follow_yes);
                                }
                            }
                        });
            }
        });

        //模型
        ClickUtils.applySingleDebouncing(tvUserInfoModelNum, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUserId.isEmpty()) {
                    return;
                }
                if (CommonConfiguration.isLogin(kv)) {
                    CommentModelActivity.start(UserInfoActivity.this, mUserId);
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(UserInfoActivity.this);
                }
            }
        });

        ClickUtils.applySingleDebouncing(tvUserInfoChat, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //聊天
                if (!mUserId.isEmpty()) {
                    if (CommonConfiguration.isLogin(kv)) {
                        ChatDetailActivity.start(UserInfoActivity.this, mUserId);
                    } else {
//                        ToastUtils.showShort(getString(R.string.http_token_error));
                        LoginVerificationCodeActivity.start(UserInfoActivity.this);
                    }
                }
            }
        });

        userInfoRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mLastId = "";
                articleIdList.clear();
                homeFollowData(true);
            }
        });
        userInfoRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                homeFollowData(false);
            }
        });

    }

    @Override
    protected void getExtras(Bundle bundle) {
        mUserId = bundle.getString("userId", "");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initUserInfo();
        homeFollowData(true);
    }

    private void initUserInfo() {
        if (mUserId.isEmpty()) {
            return;
        }
        EasyHttp.post(this)
                .api(new UserInfoApi().setUserId(mUserId))
                .request(new HttpCallback<HttpData<LoginInfoResponse>>(this) {
                    @Override
                    public void onSucceed(HttpData<LoginInfoResponse> result) {
                        if (result.getData() != null) {
                            checkUserListFollow();
                            loginInfo = result.getData();
                            //昵称
                            if (!TextUtils.isEmpty(result.getData().getNickName())) {
                                tvUserInfoName.setText(result.getData().getNickName());
                            }
                            //头像
                            if (!TextUtils.isEmpty(result.getData().getAvatar())) {
                                Glide.with(UserInfoActivity.this)
                                        .asBitmap()
                                        .load(CommonConfiguration.splitResUrl(3, result.getData().getAvatar()))
                                        .centerCrop()
                                        .placeholder(R.drawable.icon_head_portrait)
                                        .error(R.drawable.icon_head_portrait)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                                        .into(new BitmapImageViewTarget(ivUserInfoHeadPortrait) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                super.setResource(resource);
                                                ivUserInfoHeadPortrait.setImageBitmap(ImageUtils.toRound(resource));
                                            }
                                        });
                            }

                            //背景图
                            if (!TextUtils.isEmpty(result.getData().getBackgroundImage())) {
                                Glide.with(UserInfoActivity.this)
                                        .asBitmap()
                                        .load(CommonConfiguration.splitResUrl(6, result.getData().getBackgroundImage()))
                                        .fitCenter()
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .into(new BitmapImageViewTarget(ivUserInfoBackgroundImage) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                super.setResource(resource);
                                                ivUserInfoBackgroundImage.setImageBitmap(resource);
                                            }
                                        });
                            }

                            //性别
                            if (result.getData().getGender() > 0) {
                                Glide.with(UserInfoActivity.this)
                                        .load(result.getData().getGender() == 1 ? R.drawable.icon_man : R.drawable.icon_woman)
                                        .centerInside()
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .into(ivUserInfoGender);
                            }

                            //职业
                            if (!TextUtils.isEmpty(result.getData().getProvince())) {
                                tvUserInfoJob.setText("家乡:" + result.getData().getProvince());
                            }

                            if (!TextUtils.isEmpty(result.getData().getCareer())) {
                                tvUserInfoTitle.setText(result.getData().getCareer());
                            }

                            //专业领域/爱好
                            if (result.getData().getSpeciality() != null && result.getData().getSpeciality().size() > 0) {
                                specialityAdapter.setList(result.getData().getSpeciality());
                                rvUserInfoRecycler.setVisibility(View.VISIBLE);
                            } else {
                                rvUserInfoRecycler.setVisibility(View.GONE);
                            }

                            //模型数
                            tvUserInfoModelNum.setText(String.valueOf(result.getData().getModelCount()));

                            //个人介绍
                            if (!TextUtils.isEmpty(result.getData().getDesc())) {
                                llUserInfoCenterAll.setVisibility(View.VISIBLE);
                                tvUserInfoDetails.setText(result.getData().getDesc());
                            } else {
                                llUserInfoCenterAll.setVisibility(View.GONE);
                            }
                        }
                    }
                });
    }

    private void checkUserListFollow() {
        if (mUserId.isEmpty()) {
            return;
        }
        if (CommonConfiguration.isLogin(kv)) {
            List<String> userIdList = new ArrayList<>();
            userIdList.add(mUserId);
            EasyHttp.post(this)
                    .api(new CheckFollowListUserApi().setUserIdList(userIdList))
                    .request(new HttpCallback<HttpData<CheckFollowListUserApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckFollowListUserApi.Bean> result) {
                            if (result != null && result.getData() != null) {
                                isFollow = result.getData().getList().get(0).isFollow();
                                if (isFollow) {
                                    tvUserInfoIsFollow.setBackgroundResource(R.drawable.icon_follow_not);
                                } else {
                                    tvUserInfoIsFollow.setBackgroundResource(R.drawable.icon_follow_yes);
                                }
                            }
                        }
                    });
        }
    }

    private void homeFollowData(boolean isRefresh) {
        if (mUserId.isEmpty()) {
            return;
        }
        mLastId = isRefresh ? "" : mLastId;
        EasyHttp.post(this)
                .api(new HomeFindApi().setLastId(mLastId).setPageSize(CommonConfiguration.page).setSearchText("").setAuthorUserId(mUserId).setSortType(1))
                .request(new HttpCallback<HttpData<HomeFindApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<HomeFindApi.Bean> result) {
                        userInfoRefresh.finishRefresh();
                        userInfoRefresh.finishLoadMore();
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            mLastId = result.getData().getList().get(result.getData().getList().size() - 1).getId();
                            if (isRefresh) {
                                userInfoArticleAdapter.setList(result.getData().getList());
                            } else {
                                userInfoArticleAdapter.addData(result.getData().getList());
                            }
                        } else {
                            if (isRefresh) {
                                userInfoArticleAdapter.setList(new ArrayList<>());
                                userInfoArticleAdapter.setEmptyView(R.layout.empty_view_layout);
                            }
                        }

                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            for (ArticleResponse item : result.getData().getList()) {
                                articleIdList.add(item.getId());
                            }
                        }
                        checkUserListCollect();
                    }
                });
    }

    private void checkUserListCollect() {
        if (CommonConfiguration.isLogin(kv)) {
            EasyHttp.post(this)
                    .api(new CheckCollectListUserApi().setArticleIdList(articleIdList))
                    .request(new HttpCallback<HttpData<CheckCollectListUserApi.Bean>>(this) {
                        @Override
                        public void onSucceed(HttpData<CheckCollectListUserApi.Bean> result) {
                            if (result != null && result.getData() != null && result.getData().getLikes().size() > 0) {
                                userInfoArticleAdapter.setArticleState(result.getData().getLikes());
                            }
                        }
                    });
        }
    }


    @Override
    public void details(String articleId) {
        ArticleDetailsActivity.start(this, articleId, false);
    }

    @Override
    public void imageUrl(String url) {
        ScanImageDialog.getInstance(this, url).builder().setNegativeButton().show();
    }

    @Override
    public void collect(String articleId, boolean isCollect) {
        EasyHttp.post(this)
                .api(new CollectArticleApi().setArticleId(articleId).setLikes(isCollect))
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        checkUserListCollect();
                        if (isCollect) {
                            ToastUtils.showShort("已收藏");
                        } else {
                            ToastUtils.showShort("取消收藏");
                        }
                    }
                });
    }
}
